package com.youku.expression.environment;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class EnvironmentFactory {

	private static Map<String, GlobalEnvironment> factory = new LinkedHashMap<>();

	public static final GlobalEnvironment getEnvironment(String projectId) {
		GlobalEnvironment environment = factory.get(projectId);
		if (environment == null) {
			environment = new GlobalEnvironment();
			factory.put(projectId, environment);
		}
		return environment;
	}

	public static final void buildGlobal(String projectId, String key, Object value) {
		GlobalEnvironment environment = getEnvironment(projectId);

		environment.put(key, value);

		factory.put(projectId, environment);
	}

	public static final void buildLocal(String projectId, String caseId, String key, Object value) {
		GlobalEnvironment global = getEnvironment(projectId);

		if (global == null) {
			global = new GlobalEnvironment();
		}

		Environment local = global.getEnvironment(caseId);

		if (local == null) {
			local = new LocalEnvironment(global);
		}

		local.put(key, value);

		global.putEnvironment(caseId, local);

		factory.put(projectId, global);
	}

	public static final String environmentToString() {
		StringBuilder builder = new StringBuilder();
		for (Entry<String, GlobalEnvironment> entry : factory.entrySet()) {
			builder.append("项目").append(entry.getKey()).append('\n').append(entry.getValue()).append('\n');
		}
		return builder.toString();
	}

	/**
	 * 清除指定项目的全局和局部变量信息
	 * 
	 * @param projectId
	 */
	public static final void clearGlobal(String projectId) {
		factory.remove(projectId);
	}

	/**
	 * 清除指定项目的所有局部变量信息
	 * 
	 * @param projectId
	 *            项目id
	 */
	public static final void clearLocal(String projectId) {
		GlobalEnvironment environment = factory.get(projectId);
		if (environment != null) {
			environment.clearInner();
			factory.put(projectId, environment);
		}
	}
}
